package org.xiaog.fastdao;

import org.xiaog.fastdao.annotation.TableColumn;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiaog
 */
public class ResultMapping<E> {

    private static final Map<Class,ResultMapping> CACHE = new ConcurrentHashMap<>();

    public static <E> ResultMapping<E> getInstance(Class<E> eClass) {
        ResultMapping<E> resultMapping = CACHE.get(eClass);
        if (resultMapping == null) {
            resultMapping = new ResultMapping<>(eClass);
            CACHE.putIfAbsent(eClass,resultMapping);
        }
        return resultMapping;
    }

    /**
     * column-field
     */
    private final String[][] mapping;

    private ResultMapping(Class<E> eClass) {
        Field[] fs = eClass.getDeclaredFields();
        mapping = new String[fs.length][2];
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            String fn = f.getName();
            mapping[i][1] = fn;
            TableColumn tableColumn = f.getAnnotation(TableColumn.class);
            if (tableColumn != null && tableColumn.value().length() > 0) {
                mapping[i][0] = tableColumn.value();
            }else {
                mapping[i][0] = underline(fn);
            }
        }
    }

    public String[][] getMapping() {
        return mapping;
    }

    public String getField(String columnName) {
        for (String[] entry : mapping) {
            if (entry[0].equals(columnName)) {
                return entry[1];
            }
        }
        return null;
    }

    public String getColumn(String fieldName) {
        for (String[] entry : mapping) {
            if (entry[1].equals(fieldName)) {
                return entry[0];
            }
        }
        return null;
    }

    public static String underline(String name) {
        name = name.replaceAll("[A-Z]", "_$0").toLowerCase();
        return name.startsWith("_")?name.substring(1):name;
    }

}
